export function formatDate(date, fmt) {
  if (date === null || date === undefined) return ""
  date = new Date(date)
  fmt = fmt || "yyyy-MM-dd"
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      String(date.getFullYear()).substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = String(o[k])
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ("00" + str).substr(str.length)
}

export function getTransferValue(data, value) {
  let res = []
  for (let i = 0; i < value.length; i++) {
    for (let j = 0; j < data.length; j++) {
      // eslint-disable-next-line eqeqeq
      if (value[i] == data[j].col_name) {
        res.push(data[j])
      }
    }
  }
  return res
}

export function getAddField(data, value) {
  for (let i = 0; i < value.length; i++) {
    for (let j = 0; j < data.length; j++) {
      // eslint-disable-next-line eqeqeq
      if (data[j] && value[i] == data[j].col_name) {
        // eslint-disable-next-line eqeqeq
        if (value[i] == data[j].col_name) {
          delete data[j]
        }
      }
    }
  }
  return data
}

// 对象和数组深度拷贝
export function deepCopy(source) {
  if (typeof source !== "object") {
    return source;
  }
  if (source === null) {
    return source;
  }
  var newObj = source.constructor === Array ? [] : {}; // 开辟一块新的内存空间
  for (var i in source) {
    newObj[i] = deepCopy(source[i]);
  }
  return newObj;
}

// 按照每3位逗号分隔,字符串截子串法
export function toCommaFormat(number) {
  // 如果是数字，则转换为字符串
  if (typeof number === "number") {
    number = String(number)
  }

  var pointIndex = number.lastIndexOf("."); // 获取小数点的位置
  var hasDecimal = pointIndex !== -1; // 检查是否包含小数点
  var numberInteger = hasDecimal ? number.substring(0, pointIndex) : number; // 获取数的整数部分
  var length = numberInteger.length;
  if (length > 3) {
    var numberFormat = "";
    // 从尾部往前截子串拼接
    for (var i = numberInteger.length; i > 0; i = i - 3) {
      // 当前子串+之前拼接好的子串(因：substring(0,1) == substring(-2,1)，故无需判断i-3为负数的情况)
      numberFormat = numberInteger.substring(i - 3, i) + (numberFormat === "" ? "" : ("," + numberFormat));
    }
    // 整数部分+小数部分
    var numberDecimal = hasDecimal ? number.substring(pointIndex) : "";
    return numberFormat + numberDecimal;
  }
  // 无需分隔，直接返回
  return number;
}

